package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaContans;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.controller.v1.WmNewsController;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.messaging.tcp.TcpOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${fdfs.url}")
    private String fdfsUrl;

    /**
     * 查询所有自媒体文章
     *
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //校验参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //分页
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //根据状态条件查询
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //根据标题模糊查询
        if (dto.getKeyword() != null) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //根据频道列表查询
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        //根据发布时间范围查询
        if (dto.getBeginPubdate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }
        //查询当前登录的用户id
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        //按照创建时间倒序排序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        IPage<WmNews> pageResult = page(page, wrapper);
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        responseResult.setData(pageResult.getRecords());
        responseResult.setHost(fdfsUrl);
        return responseResult;
    }

    /**
     * 自媒体文章发布
     *
     * @param dto
     * @param isSubmit 是否为提交 1 为提交 0为草稿
     * @return
     */
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        //参数校验
        if (dto == null || StringUtils.isEmpty(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存或修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //如果前端传入封面是自动时
        if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        //保存图片
        if (dto.getImages() != null) {
            wmNews.setImages(dto.getImages().toString()
                    .replace("[", "")
                    .replace("]", "")
                    .replace(fdfsUrl, "")
                    .replace(" ", ""));
        }
        //保存或修改文章
        wmNews.setStatus(isSubmit);
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //默认上架
        wmNews.setEnable(WemediaContans.WM_COVER_REFERENCE);
        boolean flag = false;
        if (dto.getId() == null) {
            //提交
            flag = save(wmNews);
        } else {
            //如果是修改,要先删除文章和素材的关系
            LambdaUpdateWrapper<WmNewsMaterial> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
            wmNewsMaterialMapper.delete(wrapper);
            //修改
            flag = updateById(wmNews);
        }

        //文章自动审核的接口
        //发送消息
        if (flag) {
            kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(wmNews.getId()));
        }


        //关联文章和素材的关系
        List<Map> list = JSON.parseArray(dto.getContent(), Map.class);
        List<String> materials = new ArrayList<>();
        for (Map map : list) {
            if (map.get("type") == WemediaContans.WM_NEWS_TYPE_IMAGE) {
                String imageUrl = (String) map.get("value");
                imageUrl = imageUrl.replace(fdfsUrl, "");
                materials.add(imageUrl);
            }
        }
        //关联内容中的图片与素材的关系
        if (isSubmit == WmNews.Status.SUBMIT.getCode() && materials.size() != 0) {
            ResponseResult responseResult = saveRelativeInfoForContent(materials, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        //关联封面中的图片与素材的关系,设置wm_news的type,自动
        if (isSubmit == WmNews.Status.SUBMIT.getCode()) {
            ResponseResult responseResult = saveRelativeInfoForCover(dto, materials, wmNews);
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
    }

    /**
     * 设置封面图片与素材的关系
     *
     * @param dto
     * @param materials
     * @param wmNews
     * @return
     */
    private ResponseResult saveRelativeInfoForCover(WmNewsDto dto, List<String> materials, WmNews wmNews) {
        List<String> images = dto.getImages();
        //代表自动匹配封面
        if (dto.getType().equals(WemediaContans.WM_NEWS_TYPE_AUTO)) {
            //判断内容中的图片数量小于等于2  设置为单图
            if (materials.size() > 0 && materials.size() <= 2) {
                wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else if (materials.size() > 2) {
                //如果内容中的图片大于2 则设置为多图
                wmNews.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else {
                //内容中没有图片，则是无图
                wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
            }
            //修改文章信息
            if (images != null && images.size() > 0) {
                wmNews.setImages(images.toString().replace("[", "")
                        .replace("]", "").replace(fdfsUrl, "")
                        .replace(" ", ""));

            }
            updateById(wmNews);
        }
        //保存封面图片与素材的关系
        if (images != null && images.size() > 0) {
            ResponseResult responseResult = saveRelativeInfoForImage(images, wmNews.getId());
            if (responseResult != null) {
                return responseResult;
            }
        }
        return null;
    }

    /**
     * @param images
     * @param newsId
     * @return
     */
    private ResponseResult saveRelativeInfoForImage(List<String> images, Integer newsId) {
        List<String> materials = new ArrayList<>();
        for (String image : images) {
            materials.add(image.replace(fdfsUrl, ""));
        }

        return saveRelativeInfo(materials, newsId, WemediaContans.WM_COVER_REFERENCE);
    }


    /**
     * 保存素材与文章内容的关系
     *
     * @param materials
     * @param newsId
     * @return
     */
    private ResponseResult saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        return saveRelativeInfo(materials, newsId, WemediaContans.WM_NEWS_NONE_IMAGE);
    }

    /**
     * 保存关系
     *
     * @param materials
     * @param newsId
     * @param
     * @return
     */
    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    private ResponseResult saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        //获取数据库中的素材信息
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(WmMaterial::getUrl, materials);
        wrapper.eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId());
        List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(wrapper);
        //通过图片获取素材的id;

        List<String> materialIds = new ArrayList<>();
        if (dbMaterials != null && dbMaterials.size() != 0) {
            for (WmMaterial wmMaterial : dbMaterials) {
                materialIds.add(String.valueOf(wmMaterial.getId()));
                if ("null".equals(wmMaterial.getId())) {
                    return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
                }
            }
        }
        //批量保存素材文章表
        for (String materialId : materialIds) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(Integer.valueOf(materialId));
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            this.wmNewsMaterialMapper.insert(wmNewsMaterial);
        }
        return null;
    }

    /**
     * 根据文章id查询文章
     *
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //结果返回
        ResponseResult responseResult = PageResponseResult.okResult(wmNews);
        responseResult.setHost(fdfsUrl);
        return responseResult;
    }

    /**
     * 删除文章
     *
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在!!");
        }
        //判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode()) && wmNews.getEnable().equals(WemediaContans.WM_NEWS_SINGLE_IMAGE)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //去除素材与文章的关系
        LambdaUpdateWrapper<WmNewsMaterial> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId());
        wmNewsMaterialMapper.delete(wrapper);
        //删除文章
        removeById(wmNews.getId());
        return PageResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章上架或下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //参数校验
        if (dto == null || dto.getEnable() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在!!");
        }
        //查看文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //.修改文章状态，同步到app端（后期做）
        if (dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2) {

            //发送kafka消息
            if (wmNews.getArticleId() != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("enable", dto.getEnable());
                map.put("articleId", wmNews.getArticleId());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            }

            LambdaUpdateWrapper<WmNews> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(WmNews::getEnable, dto.getEnable()).eq(WmNews::getId, dto.getId());
            update(wrapper);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询需要发布的文章id列表
     *
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getStatus, "8")
                .lt(WmNews::getPublishTime, new Date());

        List<WmNews> list = list(wrapper);

        return list.stream().map(WmNews::getId).collect(Collectors.toList());
    }

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 分页查询文章信息
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findListAndPage(NewsAuthDto dto) {
        //检查参数
        dto.checkParam();
        //设置起始页
        //  dto.setPage((dto.getPage() - 1) * dto.getSize());
        PageHelper.startPage(dto.getPage(), dto.getSize());
        //2.分页查询
        List<WmNewsVo> list1 = wmNewsMapper.findListAndPage(dto);
        PageInfo<WmNewsVo> list = new PageInfo<>(list1);
        //统计条数
        int count = wmNewsMapper.findListCount(dto);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), count);
        pageResponseResult.setData(list.getList());
        return pageResponseResult;
    }

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //查询文章信息
        WmNews wmNews = wmNewsMapper.selectById(id);
        //查询作者信息
        WmUser wmUser = null;
        if (wmNews.getUserId() != null && wmNews != null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        //封装WmNewsVo
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        if (wmUser != null) {
            wmNewsVo.setAuthorName(wmUser.getName());
        }

        return wmNewsVo;
    }
}
